package com.gewu.pm.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;

import androidx.annotation.Nullable;

/**
 * 原始圆环进度控件（仅作参考，不要使用）
 * 
 * 这是修改前的原始版本，保留作为参考对比
 * 实际使用请用 RingProgressViewFixed
 * 
 * 原始版本的问题：
 * 1. 只支持单一进度显示
 * 2. 文字容易重叠
 * 3. 圆环宽度固定
 * 4. 缺少空指针保护
 * 5. 不支持多进度段
 */
public class RingProgressView extends View {

    private Paint mBackgroundPaint;
    private Paint mProgressPaint;
    private Paint mTextPaint;
    private RectF mRectF;
    
    private float mRadius = 100f;
    private float mStrokeWidth = 30f; // 原始版本圆环较宽
    private float mAnimatedProgress = 0f;
    private float mTargetProgress = 0f;
    
    private int mSubmittedCount = 0;
    private int mUnsubmittedCount = 0;
    private int mTotalCount = 0;
    
    private ValueAnimator mAnimator;
    
    // 动画相关
    private static final int ANIMATION_DURATION = 1000;
    private static final float START_ANGLE = -90f;
    
    // 颜色（原始版本）
    private static final int BACKGROUND_COLOR = Color.parseColor("#F0F0F0");
    private static final int PROGRESS_COLOR = Color.parseColor("#4CAF50"); // 原始是绿色

    public RingProgressView(Context context) {
        super(context);
        init();
    }

    public RingProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RingProgressView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        // 背景画笔
        mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBackgroundPaint.setColor(BACKGROUND_COLOR);
        mBackgroundPaint.setStyle(Paint.Style.STROKE);
        mBackgroundPaint.setStrokeWidth(mStrokeWidth);
        mBackgroundPaint.setStrokeCap(Paint.Cap.ROUND);
        
        // 进度画笔（原始版本只有一个）
        mProgressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mProgressPaint.setColor(PROGRESS_COLOR);
        mProgressPaint.setStyle(Paint.Style.STROKE);
        mProgressPaint.setStrokeWidth(mStrokeWidth);
        mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
        
        // 文字画笔
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(Color.parseColor("#333333"));
        mTextPaint.setTextAlign(Paint.Align.CENTER);
        mTextPaint.setTextSize(48f);
        
        mRectF = new RectF();
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        
        int size = Math.min(w, h);
        mRadius = (size - mStrokeWidth) / 2f;
        
        float centerX = w / 2f;
        float centerY = h / 2f;
        
        mRectF.set(
            centerX - mRadius,
            centerY - mRadius,
            centerX + mRadius,
            centerY + mRadius
        );
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        
        // 绘制背景圆环
        canvas.drawArc(mRectF, 0, 360, false, mBackgroundPaint);
        
        // 绘制进度圆环（原始版本只有一个进度）
        if (mAnimatedProgress > 0) {
            float sweepAngle = 360 * mAnimatedProgress;
            canvas.drawArc(mRectF, START_ANGLE, sweepAngle, false, mProgressPaint);
        }
        
        // 绘制中心文字（原始版本容易重叠）
        drawCenterText(canvas);
    }

    private void drawCenterText(Canvas canvas) {
        float centerX = getWidth() / 2f;
        float centerY = getHeight() / 2f;
        
        // 计算百分比
        int percentage = Math.round(mAnimatedProgress * 100);
        String percentText = percentage + "%";
        
        // 绘制百分比（原始版本文字布局简单，容易重叠）
        mTextPaint.setTextSize(48f);
        mTextPaint.setColor(Color.parseColor("#333333"));
        Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
        float textHeight = fontMetrics.descent - fontMetrics.ascent;
        canvas.drawText(percentText, centerX, centerY - textHeight / 4f, mTextPaint);
        
        // 绘制已交进度文字
        String progressText = mSubmittedCount + "/" + mTotalCount;
        mTextPaint.setTextSize(24f);
        mTextPaint.setColor(Color.parseColor("#666666"));
        canvas.drawText(progressText, centerX, centerY + textHeight / 2f, mTextPaint);
    }

    /**
     * 设置进度（原始版本方法）
     * @param progress 进度值 0.0-1.0
     * @param submittedCount 已交数量
     * @param totalCount 总数量
     */
    public void setProgress(float progress, int submittedCount, int totalCount) {
        mTargetProgress = Math.max(0f, Math.min(1f, progress));
        mSubmittedCount = submittedCount;
        mTotalCount = totalCount;
        
        startAnimation();
    }

    private void startAnimation() {
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.cancel();
        }
        
        mAnimator = ValueAnimator.ofFloat(0f, mTargetProgress);
        mAnimator.setDuration(ANIMATION_DURATION);
        mAnimator.setInterpolator(new LinearInterpolator());
        mAnimator.addUpdateListener(animation -> {
            mAnimatedProgress = (float) animation.getAnimatedValue();
            invalidate();
        });
        mAnimator.start();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mAnimator != null && mAnimator.isRunning()) {
            mAnimator.cancel();
        }
    }
}
